//
//  MainModule.m
//  bsl-sdk
//
//  Created by Fanty on 13-12-5.
//
//

#import "MainModule.h"
#import <chameleon-ios-sdk/CApplication.h>
#import <JSONKit.h>
#import <chameleon-ios-sdk/Library/UIDevice+IdentifierAddition.h>

#import "MainUtils.h"
#import "RolesModel.h"
#import "IsolatedStorageFile.h"

#import "DataCenter.h"

#import "AsyncTask.h"
#import "ASIFormDataRequest.h"
#import "ApiConstant.h"

#import "AppValidate.h"
#import "AppValidateParser.h"
#import "SplashViewController.h"
#import "AppInfoModel.h"
#import "AppInfoParser.h"

#define NOTPROMISS    1
#define SERVER_ERROR  2
#define APP_UPDATE    3

@interface MainModule()<UIAlertViewDelegate>

//应用验证
-(void)checkAppVaildate;

//应用版本检测
-(void)checkAppVersion;

//应用签到
-(void)registerDevice;

@end

@implementation MainModule

-(id)init{
    self=[super init];
    
    if(self){
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(registerDevice) name:@"CubeAuth_Success" object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(registerDevice) name:@"CubeAuthSync_Success" object:nil];
    }
    
    return self;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


-(UIViewController*)startMainViewControllerWithParams:(NSDictionary*)dict{
    return [[SplashViewController alloc] init];
}

- (BOOL)application:(CApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions{
    return YES;
}

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)_deviceToken{
    
    NSString *token = [[_deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    [DataCenter defaultCenter].deviceToken = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
}

-(void)startDispatchAsync{
    [IsolatedStorageFile copyFolderAtPath:[IsolatedStorageFile cordovaResourceDirectory] toPath:[IsolatedStorageFile cordovaRootDirectory] error:nil];
}

-(void)finishDispatchAsync{
    [self checkAppVaildate];
}


-(AsyncTask*)asyncWithOperation:(ASIHTTPRequest*)operation parser:(id<ParserDelegate>)parser{
    AsyncTask* task=[[AsyncTask alloc] init];
    task.request=operation;
    task.parser=parser;
    [task start];
    return task;
}


-(ASIFormDataRequest*)requestWithURL:(NSURL*)url{
    ASIFormDataRequest* request=[ASIFormDataRequest requestWithURL:url];
    [request setPostValue:[ApiConstant defaultConstant].appKey forKey:@"appKey"];
    [request setPostValue:[[UIDevice currentDevice] uniqueDeviceIdentifier] forKey:@"deviceId"];
    [request setPostValue:[[NSBundle mainBundle] bundleIdentifier] forKey:@"appId"];
    request.timeOutSeconds=10.0f;
    request.persistentConnectionTimeoutSeconds=10.0f;
    return request;
}


-(void)checkAppVaildate{
    ASIFormDataRequest* request=[ASIFormDataRequest requestWithURL:[[ApiConstant defaultConstant] appCheckClient]];
    [request setPostValue:[ApiConstant defaultConstant].appKey forKey:@"appKey"];
    [request setPostValue:[ApiConstant defaultConstant].appSecret forKey:@"secret"];
    
    AsyncTask* task=[self asyncWithOperation:request parser:[[AppValidateParser alloc] init]];
    __block AsyncTask* __task=task;
    [task setFinishBlock:^{
        if([__task result]!=nil){
            AppValidate* validate=[__task result];
            [DataCenter defaultCenter].appToken=validate.token;
            [DataCenter defaultCenter].appTokeExpired=validate.expired;
            
            [self checkAppVersion];
        }
        else if([__task statusCode]==403 || [__task statusCode]==400){
            UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:@"应用没有授于权限" message:nil delegate:self cancelButtonTitle:@"退出" otherButtonTitles:nil, nil];
            alertView.tag=NOTPROMISS;
            [alertView show];
        }
        else{
            UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:@"服务器异常，请重试" message:nil delegate:self cancelButtonTitle:@"退出" otherButtonTitles:@"重试", nil];
            alertView.tag=SERVER_ERROR;
            [alertView show];
        }
    }];
}

-(AsyncTask*)checkAppVersionTask{
    ASIHTTPRequest* request=[ASIHTTPRequest requestWithURL:[[ApiConstant defaultConstant] appVersionCheck]];
    request.timeOutSeconds=10.0f;
    request.persistentConnectionTimeoutSeconds=10.0f;
    AsyncTask* task=[self asyncWithOperation:request parser:[[AppInfoParser alloc] init]];
    return task;
}

-(void)checkAppVersion{
    AsyncTask* task=[self checkAppVersionTask];
    __block AsyncTask* __task=task;
    [task setFinishBlock:^{
        if([__task result]!=nil){
            AppInfoModel* appInfoModel=[__task result];
            int newBuild = appInfoModel.build;
            int currentBuild = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] intValue];
            if (newBuild > currentBuild){
                NSString *currentVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
                [DataCenter defaultCenter].plist=appInfoModel.plist;
                NSString *message = [NSString stringWithFormat:@"当前版本:%@\n最新版本:%@\n版本说明:\n%@", currentVersion, appInfoModel.version, appInfoModel.releaseNote];
                
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[ NSString stringWithFormat:@"%@平台版本更新",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"] ] message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
                alertView.tag=APP_UPDATE;
                [alertView show];
            }
            else{
                [[CApplication sharedApplication] redirectToModulePage:@"Module" params:nil];
                [self registerDevice];
            }
            
        }
        else{
            [[CApplication sharedApplication] redirectToModulePage:@"Module" params:nil];
            [self registerDevice];
            
        }
    }];
}

-(void)registerDevice{
    if([[DataCenter defaultCenter].deviceToken length]>0){
        
        NSMutableString* str=[[NSMutableString alloc] initWithCapacity:2];
        [str appendString:@"{"];
        [str appendFormat:@"\"%@\":\"%@\",",@"deviceId",[[UIDevice currentDevice] uniqueDeviceIdentifier]];
        [str appendFormat:@"\"%@\":\"%@\",",@"appId",[ApiConstant defaultConstant].appKey];
        [str appendFormat:@"\"%@\":\"%@\",",@"pushToken",[DataCenter defaultCenter].deviceToken];
        if([ApiConstant defaultConstant].sandBoxEnviroment)
        [str appendFormat:@"\"%@\":\"%@\",",@"channelId",@"apns_sandbox"];
        else
        [str appendFormat:@"\"%@\":\"%@\",",@"channelId",@"apns"];
        [str appendFormat:@"\"%@\":\"%@\",",@"deviceName",[[[UIDevice currentDevice] name] stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""]];
        [str appendFormat:@"\"%@\":\"%@\",",@"osName",@"IOS"];
        [str appendFormat:@"\"%@\":\"%@\",",@"build",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]];
        
        [str appendFormat:@"\"%@\":\"%@\",",@"osVersion",[[UIDevice currentDevice]systemVersion]];
        if([[DataCenter defaultCenter].username length]>0)
            [str appendFormat:@"\"%@\":\"%@\",",@"alias",[DataCenter defaultCenter].username];
        else
            [str appendFormat:@"\"%@\":\"%@\",",@"alias",@""];

        [str appendString:@"\"tags\":["];
        [str appendString:@"{"];
        if([[DataCenter defaultCenter].roles.roleName length]>0)
            [str appendFormat:@"\"key\":\"role\",\"value\":\"%@\"",[DataCenter defaultCenter].roles.roleName];
        else
            [str appendFormat:@"\"key\":\"role\",\"value\":\"%@\"",@""];
        [str appendString:@"}"];
        [str appendString:@"]"];
        [str appendString:@"}"];
        
        
        NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[[ApiConstant defaultConstant] deviceRegisterURL]];
        [request appendPostData:data];
        [request setRequestMethod:@"PUT"];
        [request startAsynchronous];
        
        __block ASIHTTPRequest* __request=request;
        [request setFailedBlock:^{
            NSLog(@"%@",[__request responseString]);
        }];
        
        [request setCompletionBlock:^{
            NSLog(@"%@",[__request responseString]);
            
        }];
        
    }
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(alertView.tag== SERVER_ERROR){
        if(buttonIndex==1)
        [self checkAppVaildate];
        else
        exit(0);
    }
    else if(alertView.tag==APP_UPDATE){
        if(buttonIndex==1){
            NSString* downloadUrl=[[ApiConstant defaultConstant] attachmentByAIdWithNoAppKey:[DataCenter defaultCenter].plist ];
            NSURL* url=[[ApiConstant defaultConstant] applicationNewVersionLink:downloadUrl];
            [[UIApplication sharedApplication] openURL:url];
        }
        else{
            [[CApplication sharedApplication] redirectToModulePage:@"Module" params:nil];
            [self registerDevice];
            
        }
    }
    else if(alertView.tag==NOTPROMISS){
        exit(0);
    }
}





@end








